
package com.jf.cloud.delivery.controller.multishop;

import cn.hutool.core.util.BooleanUtil;
import com.jf.cloud.api.auth.constant.SysTypeEnum;
import com.jf.cloud.api.auth.dto.AuthAccountDTO;
import com.jf.cloud.api.auth.feign.AccountFeignClient;
import com.jf.cloud.api.auth.vo.AuthAccountVO;
import com.jf.cloud.api.delivery.vo.StationVO;
import com.jf.cloud.api.leaf.feign.SegmentFeignClient;
import com.jf.cloud.api.platform.constant.OfflineHandleEventType;
import com.jf.cloud.api.platform.dto.OfflineHandleEventDTO;
import com.jf.cloud.api.platform.feign.OfflineHandleEventFeignClient;
import com.jf.cloud.api.platform.vo.OfflineHandleEventVO;
import com.jf.cloud.common.constant.Constant;
import com.jf.cloud.common.constant.DistributedIdKey;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.common.util.IpHelper;
import com.jf.cloud.delivery.dto.StationDTO;
import com.jf.cloud.delivery.model.Station;
import com.jf.cloud.delivery.service.StationService;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

/**
 * 自提点信息
 *
 * @author zz
 * @date 2020-12-07 15:10:01
 */
@RestController("multishopStationController")
@RequestMapping("/m/station")
@Tag(name = "[商家端]自提点信息")
public class StationController {

    @Value("${jfcloud.expose.permission:}")
    private Boolean permission;
    @Autowired
    private AccountFeignClient accountFeignClient;
    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private OfflineHandleEventFeignClient offlineHandleEventFeignClient;
    @Autowired
    private SegmentFeignClient segmentFeignClient;
    @Autowired
    private StationService stationService;

    @GetMapping("/page")
    @Operation(summary = "获取自提点信息列表" , description = "分页获取自提点信息列表")
    public ServerResponseEntity<PageVO<StationVO>> page(@Valid PageDTO pageDTO, StationDTO stationDTO) {
        Long shopId = AuthUserContext.get().getTenantId();
        stationDTO.setShopId(shopId);
        PageVO<StationVO> stationPage = stationService.pageStation(pageDTO, stationDTO);
        return ServerResponseEntity.success(stationPage);
    }

    @GetMapping
    @Operation(summary = "获取自提点信息" , description = "根据stationId获取自提点信息")
    public ServerResponseEntity<StationVO> getByStationId(@RequestParam Long stationId) {
        StationVO stationVO = stationService.getByStationId(stationId);
        if (stationVO != null && stationVO.getStatus() == -1) {
            stationVO = null;
        }
        return ServerResponseEntity.success(stationVO);
    }

    @PostMapping
    @Operation(summary = "保存自提点信息" , description = "保存自提点信息")
    public ServerResponseEntity<Void> save(@Valid @RequestBody StationDTO stationDTO) {
        Station station = mapperFacade.map(stationDTO, Station.class);
        station.setShopId(AuthUserContext.get().getTenantId());
        station.setStationId(null);
        station.setAccount(null);
        stationService.save(station);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary = "更新自提点信息" , description = "更新自提点信息")
    public ServerResponseEntity<Void> update(@Valid @RequestBody StationDTO stationDTO) {
        Station station = mapperFacade.map(stationDTO, Station.class);
        station.setAccount(null);
        stationService.update(station);
        return ServerResponseEntity.success();
    }

    @DeleteMapping
    @Operation(summary = "删除自提点信息" , description = "根据自提点信息id删除自提点信息")
    public ServerResponseEntity<Void> delete(@RequestParam Long stationId) {
        // 删除账号
        accountFeignClient.deleteByTenantIdAndSysType(stationId, SysTypeEnum.STATION.value());
        // 删除门店
        stationService.logicDeleteById(stationId);
        return ServerResponseEntity.success();
    }

    @PostMapping("/create_account")
    @Operation(summary = "创建自提门店账号", description = "创建自提门店账号")
    public ServerResponseEntity<Void> createAccount(@RequestBody StationDTO stationDTO) {
        // 创建账号
        AuthAccountDTO authAccountDTO = new AuthAccountDTO();
        authAccountDTO.setUsername(stationDTO.getAccount());
        authAccountDTO.setPassword(stationDTO.getPassword());
        authAccountDTO.setStatus(1);
        authAccountDTO.setSysType(SysTypeEnum.STATION.value());
        authAccountDTO.setIsAdmin(1);
        authAccountDTO.setTenantId(stationDTO.getStationId());
        authAccountDTO.setCreateIp(IpHelper.getIpAddr());
        authAccountDTO.setUserId(segmentFeignClient.getSegmentId(DistributedIdKey.MALL4CLOUD_AUTH_USER).getData());
        ServerResponseEntity<Long> response = accountFeignClient.save(authAccountDTO);
        if (!response.isSuccess()) {
            return ServerResponseEntity.showFailMsg(response.getMsg());
        }
        // 更新门店信息
        Station station = new Station();
        station.setStationId(stationDTO.getStationId());
        station.setAccount(stationDTO.getAccount());
        stationService.update(station);
        return ServerResponseEntity.success();
    }

    @PutMapping("/change_account_info")
    @Operation(summary = "账号密码设置", description = "账号密码设置")
    public ServerResponseEntity<Void> changeAccountInfo(@RequestBody StationDTO stationDTO) {
        // 检查是否有权限
        if (Objects.equals(stationDTO.getStationId(), Constant.ON_LINE_STATION_ID) && BooleanUtil.isFalse(permission)) {
            throw new LuckException("没有权限进行操作");
        }
        // 更新账号密码
        AuthAccountVO accountVO = accountFeignClient.getAccountInfoByTenantId(stationDTO.getStationId(), SysTypeEnum.STATION.value()).getData();
        if (accountVO == null) {
            throw new LuckException("账号不存在");
        }
        AuthAccountDTO authAccountDTO = new AuthAccountDTO();
        BeanUtils.copyProperties(accountVO, authAccountDTO);
        authAccountDTO.setUsername(stationDTO.getAccount());
        authAccountDTO.setPassword(stationDTO.getPassword());
        authAccountDTO.setSysType(SysTypeEnum.STATION.value());
        accountFeignClient.update(authAccountDTO);
        // 更新门店信息
        Station station = new Station();
        station.setStationId(stationDTO.getStationId());
        station.setAccount(stationDTO.getAccount());
        stationService.update(station);
        return ServerResponseEntity.success();
    }

    @GetMapping("/check_station_account")
    @Operation(summary = "校验账号")
    @Parameters({
            @Parameter(name = "stationId", description = "自提点id"),
            @Parameter(name = "account", description = "自提点账号")
    })
    public ServerResponseEntity<Boolean> checkStationAccount(@RequestParam("stationId") Long stationId,
                                                             @RequestParam("account") String account) {
        AuthAccountVO accountVO = accountFeignClient.getAccountInfoByTenantId(stationId, SysTypeEnum.STATION.value()).getData();
        Integer count = accountFeignClient.countByUserNameAndSysType(account, SysTypeEnum.STATION.value()).getData();
        count = (accountVO != null && accountVO.getUsername().equals(account)) ? count-1 : count;
        if (count > 0) {
            return ServerResponseEntity.success(false);
        }
        return ServerResponseEntity.success(true);
    }

    @GetMapping("/get_offline_handle_event/{stationId}")
    @Operation(summary = "通过自提点id获取下线信息")
    @Parameter(name = "stationId", description = "自提点id", required = true)
    public ServerResponseEntity<OfflineHandleEventVO> getOfflineHandleEventByStationId(@PathVariable("stationId") Long stationId) {
        OfflineHandleEventVO offlineHandleEventVO = offlineHandleEventFeignClient.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.STATION.getValue(), stationId, null).getData();
        return ServerResponseEntity.success(offlineHandleEventVO);
    }

    @PostMapping("/audit_apply")
    @Operation(summary = "下线自提点提交审核")
    public ServerResponseEntity<Void> auditApply(@RequestBody OfflineHandleEventDTO eventDTO) {
        StationVO stationVO = stationService.getByStationId(eventDTO.getHandleId());
        if (stationVO == null) {
            // 未找到该自提点信息
            throw new LuckException("未找到相应门店");
        }
        offlineHandleEventFeignClient.updateToApply(eventDTO);
        // 更新门店状态
        Station station = new Station();
        station.setStationId(eventDTO.getHandleId());
        station.setStatus(3);
        stationService.update(station);
        return ServerResponseEntity.success();
    }
}
